package com.yyx.app1.tool.SQLite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.File;
import java.io.IOException;

public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {
    private String dbName;
    private String tableName;

    public PersonSQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
    {
        super(context, name, factory, version);
    }

    public PersonSQLiteOpenHelper(Context context,String dbName,String tableName)
    {
        super(context, dbName+".db", null, 1);
        this.dbName=dbName;
        this.tableName=tableName;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + " (number integer primary key ,address varchar ,addtime varchar ,adminId integer ,attention varchar ," +
                    "belongToColumn integer ,clinical varchar ,columnName varchar ,contraindication varchar ,cureFun varchar ,drugInteraction varchar ,effect varchar ," +
                    "englishName varchar ,explain varchar ,firstId varchar ,firstUrl varchar ,functionDosage varchar ,id varchar ,indication varchar ,medicineContent varchar," +
                    "medicineFactory varchar ,medicineImage varchar ,medicineList varchar ,medicineName varchar ,offTime varchar, onTime varchar, petName varchar," +
                    "pinyin varchar ,preparation varchar ,secondUrl varchar ,secondcolumns, varchar ,shape varchar ,status integer);");
        }
        catch (Exception e)
        {
            Log.e("异常",e.toString());
        }
    }

    @Override
    //version 版本参数改变时 被调用,用来修改表结构
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //db.execSQL("ALTER TABLE person ADD COLUMN accounts integer");
    }

    @Override
    public SQLiteDatabase getWritableDatabase() {
        SQLiteDatabase db=null;
        try {
            String dbPath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.cxlin.database";
            File dbp=new File(dbPath);
            File dbf=new File(dbPath+"/"+dbName+".db");
            if(!dbp.exists()){
                dbp.mkdir();
            }
            //数据库文件是否创建成功
            boolean isFileCreateSuccess=false;
            if(!dbf.exists()){
                isFileCreateSuccess=dbf.createNewFile();
            }
            else{
                isFileCreateSuccess=true;
            }
            if(isFileCreateSuccess)
                db = SQLiteDatabase.openOrCreateDatabase(dbf, null);
        }catch (Exception e)
        {
            Log.e("异常",e.toString());
        }
        finally {
            return db;
        }
    }
}
